﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

public partial class CustomerManagement_MoneyManagementEdit : System.Web.UI.Page
{
    private string _code;
    public string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"] : "";
        }
    }
    public DataSet Bank
    {
        get 
        {
            string where = " and PT_Bank=1 and PT_ONLINE=1";
            BLL.PAYTYPE paytype = new BLL.PAYTYPE();
            DataSet ds = paytype.GetPatTypeByWhere(where);
            return ds;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["FCode"] = "300400112";
        if (!IsPostBack)
        {
            TextBox2.Attributes.Add("onclick", "SearchVIP('../');");

            drpBank.DataSource = Bank.Tables[0];
            drpBank.DataBind();

            if (Code != "")
            {
                Model.REMITTANCE remittance = new BLL.REMITTANCE().GetModel(int.Parse(Code));
                TextBox2.Text = remittance.R_UserCode;
                txtDealNo.Text = remittance.R_NO;
                txtJE.Text = remittance.R_Amt.ToString();
                drpType.SelectedValue = remittance.R_DST;
                drpBank.SelectedValue = remittance.R_PostMethod;
                lblAccount.Text = remittance.BYZD2;
                txtNote.Text = remittance.R_Note;
                txtAddTime.Text = remittance.R_AddTime.ToString();
                if (remittance.R_Valid == 1)
                {
                    btnSave.Enabled = false;
                    btnCheck.Enabled = false;
                    btnDelete.Enabled = false;
                }
            }

            foreach (DataRow row in Bank.Tables[0].Rows)
            {
                if (row["PT_CODE"].ToString() == drpBank.SelectedValue)
                {
                    lblAccount.Text = row["PA_ACCOUNT"].ToString();
                    hdHaveDeal.Value = row["PT_HAVEDEAL"].ToString();
                }
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            /*
           为了使充值金额能退款，此处屏蔽掉

            decimal limit = decimal.Parse(new BLL.SYSPARAM().GetModel("016").SP_PARAM19);
            decimal aa = decimal.Parse(txtJE.Text.Trim());
            if (aa < limit)
            {
                Share.Alert(this, "金额必须大于最低充值金额" + limit.ToString() + "元");
                return;
            }
            */
        }
        catch
        {
            Share.Alert(this, "金额只能为数字");
            return;
        }
        if (hdHaveDeal.Value == "1" && txtDealNo.Text.Trim().Length<1)
        {
            Share.Alert(this, "所选银行交易号不能为空");
            return;
        }
        BLL.REMITTANCE bllRemittance = new BLL.REMITTANCE();

        Model.REMITTANCE remittance = null;
        if (Code == "")
        {
            if (txtDealNo.Text.Trim().Length > 0)
            {
                if (bllRemittance.CheckRepeat("", txtDealNo.Text, true, drpType.SelectedValue))
                {
                    Share.Alert(this.Page, "交易号重复");
                    return;
                }
            }
            remittance = new Model.REMITTANCE();
            remittance.R_UserCode = TextBox2.Text.Trim();
            remittance.R_PostMethod = drpBank.SelectedValue;//支付方式代码
            remittance.R_NO = txtDealNo.Text.Trim();
            remittance.R_AddTime = DateTime.Parse(txtAddTime.Text);
            remittance.R_Amt = decimal.Parse(txtJE.Text.Trim());
            remittance.R_DST = drpType.SelectedValue;
            remittance.R_Maker = Share.UserValue(0);
            remittance.R_Valid = 0;
            remittance.R_Validor = "";
            remittance.BYZD1 = drpBank.SelectedItem.Text;//银行名称
            remittance.BYZD2 = lblAccount.Text;//户主帐号
            remittance.R_Note = txtNote.Text;

            int ret = new BLL.REMITTANCE().Add(remittance);
            if (ret > 0)
            {
                Share.Alert(this.Page, "添加成功");
                Response.Redirect("MoneyManagement.aspx");
                return;
            }
        }
        else
        {
            remittance = new BLL.REMITTANCE().GetModel(int.Parse(Code));
            if (remittance.R_Valid == 1)
            {
                Share.Alert(this.Page, "此单据已被审核，不允许再次操作！"); return;
            }
            if (txtDealNo.Text.Trim().Length > 0)
            {
                if (bllRemittance.CheckRepeat(this.Code, txtDealNo.Text, false, drpType.SelectedValue))
                {
                    Share.Alert(this.Page, "交易号重复");
                    return;
                }
            }
            remittance = new BLL.REMITTANCE().GetModel(int.Parse(Code));
            remittance.R_NO = txtDealNo.Text.Trim();
            remittance.R_PostMethod = drpBank.SelectedValue;//支付方式代码
            remittance.R_Amt = decimal.Parse(txtJE.Text.Trim());
            remittance.R_DST = drpType.SelectedValue;
            remittance.BYZD1 = drpBank.SelectedItem.Text;//银行名称
            remittance.BYZD2 = lblAccount.Text;//户主帐号
            remittance.R_Note = txtNote.Text;
            remittance.R_AddTime = DateTime.Parse(txtAddTime.Text);
            bool ret = new BLL.REMITTANCE().Update(remittance);
            if (ret)
            {
                Share.Alert(this.Page, "修改成功"); return;
            }

        }
    }
    protected void btnCheck_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400112", "00010"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        /*decimal limit = decimal.Parse(new BLL.SYSPARAM().GetModel("016").SP_PARAM19);
        decimal aa = decimal.Parse(txtJE.Text.Trim());
        if (aa < limit)
        {
            Share.Alert(this, "金额必须大于最低充值金额" + limit.ToString() + "元");
            return;
        }*/
        if (Code != "")
        {
            Model.REMITTANCE remittance = new BLL.REMITTANCE().GetModel(int.Parse(Code));
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            if (remittance.R_Valid == 1)
            {
                Share.Alert(this.Page, "此单据已被审核，不允许再次操作！"); return;
            }
            else
            {
                StringBuilder StyleDB = new StringBuilder();
                StringBuilder ErpDB = new StringBuilder();

                DataSet ds = new BLL.V_VIP_ACCOUNT().GetBalanceByCustomerId(remittance.R_UserCode);
                if (ds.Tables[0].Rows.Count == 0)
                {
                    string dm = new BLL.V_VIPSET().GetModelByGKDM(remittance.R_UserCode).DM;
                    StyleDB.Append(string.Format("insert into V_VIP_ACCOUNT(DM,DQJE_1)values('{0}',{1})|", dm, 0));
                    ErpDB.Append(string.Format("insert into V_VIP_ACCOUNT(DM,DQJE_1)values('{0}',{1})|", dm, 0));
                }
                if (StyleDB.Length > 0)
                {
                    string[] cmdStyleDB = StyleDB.ToString().TrimEnd('|').Split('|');
                    string[] cmdErpDB = ErpDB.ToString().TrimEnd('|').Split('|');
                    LX_Manage.ERP.Service service = new LX_Manage.ERP.Service();
                    bool ret = service.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, cmdStyleDB, cmdErpDB);

                    if (!ret)
                    {
                        Share.Alert(this.Page, "您选择调整的会员中，有一个或多个会员没有结余款信息，当系统试图为起初始化结余款信息时，发生错误，请重新尝试审核！");
                        return;
                    }

                }

                if (remittance.R_DST == "000")
                {//充值，同时生成一张已经审核的结余款调整单，同时修改用户当前金额和可用发货金额 
                    StyleDB = new StringBuilder();
                    ErpDB = new StringBuilder();

                    string newID = new BLL.BALANCEADJUST().GetNewID();
                    BLL.Common.ADDLSH("300400102");
                    StyleDB.Append(string.Format("insert into BALANCEADJUST(BA_ID,BA_TYPE,BA_CREATER,BA_CREATEDATE,BA_CHECK,BA_CHECKER,BA_CHECKDATE,BA_RID) values('{0}','{1}','{2}','{3}',{4},'{5}','{6}','{7}')|", newID, "011", Share.UserValue(0), DateTime.Now, 1, Share.UserValue(0), DateTime.Now, this.Code));// 调整单主表


                    DataSet dsDQJE = new BLL.V_VIP_ACCOUNT().GetBalanceByCustomerId(remittance.R_UserCode);
                    decimal balance = DBUtility.SqlHelper.GetDecimal(dsDQJE.Tables[0].Rows[0]["DQJE_1"]);
                    balance = balance + remittance.R_Amt;

                    StyleDB.Append(string.Format("insert into BADETAIL(BAD_ID,BAD_DETAILCODE,BAD_CUSTOMERCODE,BAD_AMT,BAD_BALANCE,BAD_NOTE) values('{0}',{1},'{2}',{3},{4},'{5}')|", newID, 1, remittance.R_UserCode, remittance.R_Amt, balance,
                        "前台用户银行转账充值"));

                    //同步更新用户当前金额
                    string dm = new BLL.V_VIPSET().GetModelByGKDM(remittance.R_UserCode).DM;
                    StyleDB.Append(string.Format("update V_VIP_ACCOUNT set DQJE_1={0} where DM='{1}'|", balance, dm));
                    ErpDB.Append(string.Format("update V_VIP_ACCOUNT set DQJE_1={0} where DM='{1}'|", balance, dm));

                    decimal credit = new BLL.V_VIPSET().GetModelByGKDM(remittance.R_UserCode).BYZD12;//信用额度
                    decimal accountAmt = credit + balance;//账户当前余额加信用额度

                    //同步更新可用发货金额 
                    StyleDB.Append(string.Format("update v_vipset set BYZD13={0} where DM='{1}'|", accountAmt, dm));
                    ErpDB.Append(string.Format("update v_vipset set BYZD13={0} where DM='{1}'|", accountAmt, dm));
                }
                else
                {//保证金，同时生成一张已经审核的保证金调整单，同时修改用户扩展信息表的保证金
                    StyleDB = new StringBuilder();

                    string newID = new BLL.MarginAdjust().GetNewID();
                    BLL.Common.ADDLSH("300400109");

                    StyleDB.Append(string.Format("insert into MarginAdjust(MA_ID,MA_Creator,MA_CreateDate,MA_CHECK,MA_CHECKER,MA_CHECKDATE,BYZD1)values('{0}','{1}','{2}',{3},'{4}','{5}','{6}')|", newID, Share.UserValue(0), DateTime.Now, 1, Share.UserValue(0), DateTime.Now,this.Code));

                    StyleDB.Append(string.Format("insert into MarginAdjustDetail(MA_ID,MAD_ID,MAD_CustomerID,MAD_AMT,MAD_Note)values('{0}',{1},'{2}',{3},'{4}')|", newID, 1, remittance.R_UserCode, remittance.R_Amt, "前台用户银行转帐保证金"));

                    DataSet dsBYZD8 = new BLL.V_CUSTOMER_AUTO().GetMarginByCustomerId(remittance.R_UserCode);
                    decimal margin = DBUtility.SqlHelper.GetDecimal(dsBYZD8.Tables[0].Rows[0]["BYZD8"]);
                    StyleDB.Append(string.Format("update V_CUSTOMER_AUTO set BYZD8={0} where VC_CODE='{1}'|", margin + remittance.R_Amt, remittance.R_UserCode));
                }
                StyleDB.Append(string.Format("update REMITTANCE set R_VALID=1,R_VALIDOR='{0}',R_VALIDTIME='{2}' where R_ID='{1}'|", Share.UserValue(0), Code,DateTime.Now));
                string[] cmdStyle = StyleDB.ToString().TrimEnd('|').Split('|');
                string[] cmdErp = ErpDB.ToString().TrimEnd('|').Split('|');
                bool retValue = false;
                if (remittance.R_DST == "000")
                {
                    LX_Manage.ERP.Service erpService = new LX_Manage.ERP.Service();
                    retValue = erpService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, cmdStyle, cmdErp);
                }
                else
                {
                    retValue = new SQLServerDAL.ORDERDOC().Deliver(cmdStyle);
                }
                if (retValue)
                {
                    Response.Redirect("MoneyManagement.aspx");
                   
                }
                else
                {
                    Share.Alert(this.Page, "操作失败，请重新审核!");
                    return;
                }
            }

        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {

        if (Code != "")
        {
            Model.REMITTANCE remittance = new BLL.REMITTANCE().GetModel(int.Parse(Code));
            bool ret = new BLL.REMITTANCE().Delete(remittance.R_ID);
            if (!ret)
            {
                Share.Alert(this.Page, "操作失败");
                return;
            }
            Response.Redirect("MoneyManagement.aspx");
        }
    }
    protected void drpBank_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (DataRow row in Bank.Tables[0].Rows)
        {
            if (row["PT_CODE"].ToString() == drpBank.SelectedValue)
            {
                lblAccount.Text = row["PA_ACCOUNT"].ToString();
                hdHaveDeal.Value = row["PT_HAVEDEAL"].ToString();
            }
        }
    }
}
